﻿using DAL;
using BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
public partial class admincp_Products : System.Web.UI.Page
{
    DigitalWorldDataContext db = new DigitalWorldDataContext();
    ProductsBLL pro = new ProductsBLL();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string vt = Page.RouteData.Values["ViTri"].ToString();

            hlBasicProduct.NavigateUrl = "~/Quan-Ly-San-Pham/" + vt + "/" + 0;
            hTemplateManager.NavigateUrl = "~/Quan-Ly-San-Pham/" + vt + "/" + 1;
            string id = Page.RouteData.Values["id"].ToString();

            MutiView1.ActiveViewIndex = 0;
            LoadDDL_Products();
            LoadData_Products();
            btnUpdate.Enabled = false;
            rbtnDiscountinued.Enabled = false;
        }
    }

    #region Basic Information
    #region Load Supplier By CategoryID
    /// <summary>
    /// Hàm lấy dữ liệu supplier theo catid của categories
    /// </summary>
    /// <param name="CateID"></param>
    void LoadSupplierByCategory(int CateID)
    {
        var danhsach = from sc in db.menuitems
                       join s in db.manufacturers
                       on sc.manufacturerid equals s.id
                       where sc.cateid == CateID
                       select new
                       {
                           id = sc.manufacturerid,
                           companyname = s.companyname
                       };
        ddlSupplier.DataSource = danhsach;
        ddlSupplier.DataTextField = "companyname";
        ddlSupplier.DataValueField = "id";
        ddlSupplier.DataBind();
    }
    #endregion
    

    #region Load Categories - Suppliers - Origins
    /// <summary>
    /// Hàm lấy dữ liệu các bảng category,supplier theo catid, origins lên dropdownlist
    /// </summary>
    void LoadDDL_Products()
    {
        ddlCategory.DataSource = db.categories;
        ddlCategory.DataTextField = "categoryname";
        ddlCategory.DataValueField = "id";
        ddlCategory.DataBind();

        LoadSupplierByCategory(ddlCategory.SelectedIndex);
    }
    #endregion
    

    #region Load Basic Product to GridView
    /// <summary>
    /// Hàm lấy dữ liệu từ bảng product lên gridview
    /// </summary>
    void LoadData_Products()
    {
        gvProduct.DataSource = db.products.OrderByDescending(p=>p.id);
        gvProduct.DataBind();
    }

    protected void ddlCategory_SelectedIndexChanged1(object sender, EventArgs e)
    {
        LoadSupplierByCategory(ddlCategory.SelectedIndex);
    }
    #endregion
    
    #region Hàm nhận giá trị cơ bản
    /// <summary>
    /// Hàm nhận giá trị vào lớp product từ các textbox ở trang thông tin cơ bản
    /// </summary>
    /// <param name="ProID"></param>
    //void Products_BasicInfor(int ProID)
    //{
        //p.productid = ProID;
        //p.categoryid = ddlCategory.SelectedItem.Value;
        //p.originid = ddlOrigin.SelectedItem.Value;
        //p.supplierid = int.Parse(ddlSupplier.SelectedItem.Value);
        //p.productname = txtProductName.Text;
        //p.description = txtDescription.Text;
        //p.photopath = SaveImage();
        //p.dateupdated = DateTime.Now.Date;
        //p.unitprice = Decimal.Parse(txtUnitPrice.Text);
        //p.unitprice_sell = decimal.Parse(txtUnitPrice_Sell.Text);
        //p.unitsinstock = int.Parse(txtUnitsInStock.Text);
        //p.unitsonorder = int.Parse(txtUnitsOnOrder.Text);
        //p.discount = double.Parse(txtDiscount.Text);
        //if (rbtnDiscountinued.SelectedItem.Value == "1")
        //{
        //    p.discontinued = true;
        //}
        //else
        //{
        //    p.discontinued = false;
        //}
    //}
    #endregion
    
    #region Reset TextBox View Basic Product
    /// <summary>
    /// Hàm xoá trắng các textbox trên trang thông tin cơ bản
    /// </summary>
    void ResetTextBox()
    {
        txtProductName.Text = string.Empty;
        ddlCategory.SelectedIndex = 0;
        LoadSupplierByCategory(ddlCategory.SelectedIndex);
        txtOrigin.Text = string.Empty;
        txtPrice.Text = string.Empty;
        txtAmount.Text = string.Empty;
        txtweigh.Text = string.Empty;
        txtDescription.Text = string.Empty;
        imgPhotoPath.ImageUrl = null;
        txtProductName.Focus();
    }
    #endregion
    
    #region Lưu hình sản phẩm
    /// <summary>
    /// Hàm lưu hình sản phẩm từ FileUpLoad
    /// </summary>
    /// <returns></returns>
    private string SaveImage()
    {
        string savename = string.Empty;
        if (!string.IsNullOrEmpty(ful_upload.FileName.ToString()))
        {
            int count = db.products.Count();
            string tenhinh = "Digital_World_" + ddlCategory.SelectedItem.Text + "_" +
                ddlSupplier.SelectedItem.Text + "_" + count + "_" + txtProductName.Text;
            int vitri = ful_upload.FileName.LastIndexOf('.');
            string tail = ful_upload.FileName.Substring(vitri);
            if (tail.ToLower() == ".jpg" || tail.ToLower() == ".png" || tail.ToLower() == ".gif")
            {
                savename = tenhinh + tail;
                string savePath = Server.MapPath("../../Image/Products/");
                ful_upload.SaveAs(savePath + savename);
            }
        }
        return savename;
    }
    #endregion

    #region Methods Button Insert - Update - Grid View Event SelectIndexChanging
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        try
        {
            bool discontinued;
            if (rbtnDiscountinued.SelectedItem.Value == "1")
            {
                discontinued = true;
            }
            else
            {
                discontinued = false;
            }

            product p = new product
            {
                name = txtProductName.Text,
                categoryid = int.Parse(ddlCategory.SelectedItem.Value),
                providerid = int.Parse(ddlSupplier.SelectedItem.Value),
                origin = txtOrigin.Text,
                description = txtDescription.Text,
                photopath = SaveImage(),
                price = txtPrice.Text,
                amount = int.Parse(txtAmount.Text),
                weight = int.Parse(txtweigh.Text),
                status = discontinued
            };
            pro.InsertBasicProduct(p);
            this.LoadData_Products();
            ResetTextBox();
            lblThongBao.Text = "Thành công";
        }
        catch
        {
            lblThongBao.Text = "Thất bại";
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            int ProductID = int.Parse(gvProduct.SelectedRow.Cells[0].Text);
            bool discontinued;
            if (rbtnDiscountinued.SelectedItem.Value == "1")
            {
                discontinued = true;
            }
            else
            {
                discontinued = false;
            }
            product p = new product
            {
                id = ProductID,
                name = txtProductName.Text,
                categoryid = int.Parse(ddlCategory.SelectedItem.Value),
                providerid = int.Parse(ddlSupplier.SelectedItem.Value),
                origin = txtOrigin.Text,
                description = txtDescription.Text,
                photopath = SaveImage(),
                price = txtPrice.Text,
                amount = int.Parse(txtAmount.Text),
                weight = int.Parse(txtweigh.Text),
                status = discontinued
            };
            pro.UpdateBasicProduct(p);
            ResetTextBox();
            btnUpdate.Enabled = false;
            this.LoadData_Products();
            lblThongBao.Text = "Thành công";
        }
        catch
        {
            lblThongBao.Text = "Thất bại";
        }
    }
    protected void gvProduct_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        int ProductID = int.Parse(gvProduct.Rows[e.NewSelectedIndex].Cells[0].Text);
        var danhsach = db.products.SingleOrDefault(pr => pr.id.Equals(ProductID));
        txtProductName.Text = danhsach.name;
        ddlSupplier.SelectedValue = danhsach.providerid.ToString(); ;
        ddlCategory.SelectedValue = danhsach.categoryid.ToString();
        txtOrigin.Text = danhsach.origin;
        txtPrice.Text = danhsach.price;
        txtAmount.Text = danhsach.amount.ToString();
        txtweigh.Text = danhsach.weight.ToString();
        txtDescription.Text = danhsach.description;
        imgPhotoPath.ImageUrl = "~/Image/Products/" + danhsach.photopath.ToString();
        if (danhsach.status == true)
            rbtnDiscountinued.SelectedIndex = 0;
        else
            rbtnDiscountinued.SelectedIndex = 1;
        btnUpdate.Enabled = true;
        rbtnDiscountinued.Enabled = true;
    }
    #endregion

    #endregion

    protected void gvProduct_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvProduct.PageIndex = e.NewPageIndex;
        this.LoadData_Products();
    }
    protected void gvProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string ID = gvProduct.Rows[e.RowIndex].Cells[0].Text;
        pro.DeleteProduct(int.Parse(ID));
        this.LoadData_Products();       
    }
}